<?php

namespace App\Shop\Controllers;

use App\Admin\Repositories\ServiceCategory;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Validation\Rule;

class ServiceCategoryController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new ServiceCategory(), function (Grid $grid) {
            $admin = Admin::user();
            $isShop = $admin->isAdministrator();
            if ($isShop){
                $shop_id = $admin->id;
            }else{
                $shop_id = $admin->shop_id;
            }
            $grid->model()->where("shop_id",$shop_id);
            $grid->column('id')->sortable();
            $grid->column('name');
            $grid->column('sort')->sortable();
            $grid->column('status')->radio(['正常','隐藏'],true)->label(['info','default']);
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();
            $grid->quickSearch(['name']);
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new ServiceCategory(), function (Show $show) {
            $show->field('id');
            $show->field('name');
            $show->field('sort');
            $show->field('status');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new ServiceCategory(), function (Form $form) {
            $id = $form->getKey();
            $message = ['unique' => '此服务分类已存在' ];
            $rules = [
                'required'
            ];
            $admin = Admin::user();
            $isShop = $admin->isAdministrator();
            if ($isShop){
                $shop_id = $admin->id;
            }else{
                $shop_id = $admin->shop_id;
            }
            $form->hidden('shop_id')->default($shop_id)->value($shop_id);
            if($id){
                $rules[] = Rule::unique('service_category','name')->where("shop_id",$shop_id)->ignore($id);
            }else{
                $rules[] = Rule::unique('service_category','name')->where("shop_id",$shop_id);
            }
            $form->text('name')->rules($rules,$message)->required();
            $form->number('sort')->default(0);
            $form->radio('status')->options(['正常','隐藏'])->default(0);
        });
    }
}
